<template>
  <div>
<!--    面包屑导航  -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
<!--    表格卡片  -->
    <el-card class="box-card">
      <el-row :gutter="20" class="header_card">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button icon="el-icon-search" slot="append" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
<!--      表格展示用户列表-->
      <el-table :data="userList" border style="width: 100%">
        <el-table-column type="index" width="100" align="center">
        </el-table-column>
        <el-table-column prop="username" label="姓名" align="center">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" align="center">
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" align="center">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" align="center">
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" circle size="mini" @click="showEditDialogVisible(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="deleteUser(scope.row.id)"></el-button>
            <el-tooltip content="角色分配" placement="top" :enterable="false">
              <el-button type="success" icon="el-icon-setting" circle size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页管理-->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="queryInfo.pagenum"
          :page-sizes="[1,2,3,5,10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
<!--    添加用户对话框  -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible" width="50%" @close="addDialogClosed">
      <el-form :model="addForm" label-width="100px" :rules="addFormRule" ref="addFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input  autocomplete="off" v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input  autocomplete="off" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input  autocomplete="off" v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input  autocomplete="off" v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!--    修改用户对话框  -->
    <el-dialog title="修改用户" :visible.sync="editDialogFormVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" label-width="100px" :rules="editFormRule" ref="editFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    data () {
      var checkEmail = ( (rule , value , cb) => {
        const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if(regEmail.test(value)){
          return cb()
        }
        cb(new Error('请输入合法的邮箱'))
      });
      var checkMobile = ( (rule , value , cb) => {
        const regMobile = /^1(3|4|5|7|8)\d{9}$/
        if(regMobile.test(value)){
          return cb()
        }
        cb(new Error('请输入合法的手机号'))
      });
      return {
        editForm:{},
        queryInfo:{
          query:'',
          pagenum:1,
          pagesize:3
        },
        addForm:{
          username:'',
          password:'',
          email:'',
          mobile:''
        },
        userList:[],
        total:0,
        dialogFormVisible:false,
        editDialogFormVisible:false,
        addFormRule:{
          username:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
          ],
          password:[
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
          ],
          email:[
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator: checkEmail, trigger: 'blur' }
          ],
          mobile:[
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator: checkMobile, trigger: 'blur' }
          ]
        },
        editFormRule:{
          email:[
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator: checkEmail, trigger: 'blur' }
          ],
          mobile:[
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator: checkMobile, trigger: 'blur' }
          ]
        }
      }
    },
    created () {
      this.getUserList()
    },
    methods:{
      //获取用户列表
      async getUserList () {
        const { data : res } = await this.$http.get('users',{ params : this.queryInfo})
        if(res.meta.status !== 200) return this.$message.error('获取用户列表失败')
        this.userList = res.data.users
        this.total = res.data.total
        //重置当前页码
        this.queryInfo.pagenum = 1
      },
      //获取用户列表 不重置页码
      async getUserNonePageNum () {
        const { data : res } = await this.$http.get('users',{ params : this.queryInfo})
        if(res.meta.status !== 200) return this.$message.error('获取用户列表失败')
        this.userList = res.data.users
        this.total = res.data.total
      },
      //改变每页显示大小
      handleSizeChange (newSize) {
        this.queryInfo.pagesize = newSize
        this.getUserNonePageNum()
      },
      //监听页码值
      handleCurrentChange (newPage) {
        this.queryInfo.pagenum = newPage
        this.getUserNonePageNum()
      },
      //监听用户状态
      async userStateChange(userInfo) {
        const { data : res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
        if(res.meta.status !== 200) {
          userInfo.mg_state = !userInfo.mg_state
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('用户状态更新成功')
      },
      //添加用户
     addUser () {
        this.$refs.addFormRef.validate(  async (valid) => {
          if(!valid) return
          const { data : res } = await this.$http.post('users',this.addForm)
          if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success('添加用户成功')
          //隐藏对话框
          this.dialogFormVisible = false
          //更新用户列表
          this.getUserList()
        })
      },
      //监听添加用户对话框关闭
      addDialogClosed () {
        this.$refs.addFormRef.resetFields()
      },
      //显示修改用户对话框
      async showEditDialogVisible (id) {
        this.editDialogFormVisible = true
        //发请求获取对应id的全部信息
        const { data : res } = await this.$http.get(`users/${id}`)
        if(res.meta.status !== 200) return this.$message.error(res,meta.msg)
        this.editForm = res.data
      },
      //发送修改用户信息请求
      editUser(){
        this.$refs.editFormRef.validate( async valid => {
          if(!valid) return
          //发送修改用户信息的数据请求
          const { data : res } = await this.$http.put(`users/${this.editForm.id}`,{
            email:this.editForm.email,
            mobile:this.editForm.mobile
          })
          if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success('修改用户信息成功')
          this.getUserNonePageNum()
          this.editDialogFormVisible = false
        })
      },
      //监听修改用户对话框关闭
      editDialogClosed () {
        this.$refs.editFormRef.resetFields()
      },
      //删除信息弹框
      async deleteUser(id){
        const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
          // console.log(res)//confrim cancel
        if(res === 'confirm'){
          //发送请求
          const { data : result } = await this.$http.delete(`users/${id}`)
          if(result.meta.status !== 200) return this.$message.error('删除用户失败')
          this.$message.success('删除用户成功')
          this.getUserList()
        }
      }
    }
  }
</script>
<style>
  .el-breadcrumb{
    margin-bottom:10px ;
  }
  .header_card{
    margin-bottom: 10px;
  }
</style>
